const {
  APPROVEAL_TYPE, APPROVEAL_STATUS
} = require('../../../constant/index')
const {
  addApprovalRecord
} = require('../../../api/approval')
const {
  getUserBaseInformation
} = require('../../../utils/strorage')
const {
  showToast,
  to,
  openLoading,
  closeLoading,
  backParentLoad
} = getApp()
Page({
  data: {
    approvalSupplementaryWorkOrder: 0,
    formData: {
      operationContent: ''
    }
  },
  onLoad() {
    this.setData({
      orderData: JSON.parse(this.options.data)
    })
    const userInfo = getUserBaseInformation();
    const approvalSupplementaryWorkOrder = userInfo.approvalSupplementaryWorkOrder;
    this.setData({
      approvalSupplementaryWorkOrder
    })

    let title = '工单审批'
    if (approvalSupplementaryWorkOrder === 1) {
      title = '补录审批'
    }
    wx.setNavigationBarTitle({
      title,
    })
  },

  handleFieldChange(event) {
    this.setData({
      ['formData.operationContent']: event.detail
    })
  },

  handleClick(status) {
    let approvalType = APPROVEAL_TYPE.APPROVAL_CUSTOMER_WORK_ORDER
    if (this.data.approvalSupplementaryWorkOrder === 1) {
      approvalType = APPROVEAL_TYPE.APPROVAL_SUPPLEMENTARY_WORK_ORDER
    }
    const params = {
      approvalType,
      approvalStatus: status,
      approvalContent: this.data.formData.operationContent || '',
      targetId: this.data.orderData.workOrderId
    }
    this.handleSubmit(params)
  },

  async handleSubmit(params) {
    openLoading()
    const [err] = await to(addApprovalRecord(params))
    closeLoading()

    if (!err) {
      showToast({
        message: '提交成功',
        type: 'success',
        mask: true,
        onClose: () => {
          setTimeout(() => {
            backParentLoad(1)
          }, 1000)
        }
      })
    }
  },

  handleReject() {
    this.handleClick(APPROVEAL_STATUS.REJECT_APPROVAL);
  },

  handlePass() {
    this.handleClick(APPROVEAL_STATUS.PASSED_APPROVAL);
  }
})